package cn.gogpay.dcb.api.web;

import cn.gogpay.dcb.api.common.constant.BizConstant;
import cn.gogpay.dcb.api.entity.OrderRecord;
import cn.gogpay.dcb.api.service.RechargeRecordService;
import cn.gogpay.dcb.api.web.form.PreOrderForm;
import cn.gogpay.dcb.common.dto.ResultCode;
import cn.gogpay.dcb.common.dto.ResultDTO;
import cn.gogpay.dcb.h5base.white.H5BaseWhite;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author zhanglong@gogpay.cn
 * @date 2019/12/3 20:56
 */
@RestController
@RequestMapping(value = "/")
public class OrderController {
    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    @Autowired
    private RechargeRecordService rechargeRecordService;

    @PostMapping(value = "preOrder")
    @H5BaseWhite
    public ResultDTO preOrder(@RequestBody PreOrderForm preOrderForm)  {
        logger.info("preOrder----------->"  + JSONObject.toJSONString(preOrderForm));
        OrderRecord record = rechargeRecordService.findOne(preOrderForm.getRecordId());
        if (Objects.isNull(record)) {
            logger.info("订单不存在");
            return new ResultDTO(500,"订单不存在");
        }
        if (record.getPrice().setScale(2, RoundingMode.HALF_UP)
                .compareTo(new BigDecimal(preOrderForm.getAmt()).setScale(2,RoundingMode.HALF_UP)) != 0) {
            logger.info("金额不匹配--->交易中心金额" + preOrderForm.getAmt() + "----->表中的金额" + record.getBalance());
            return new ResultDTO(500,"金额不匹配");
        }
        record.setOrderNo(preOrderForm.getOrderNo());
        rechargeRecordService.save(record);
        ResultDTO resultDTO = new ResultDTO();
        resultDTO.setStatus(ResultCode.tradeSuccess().code());
        Map item = new HashMap<>();
        item.put("commodityName", BizConstant.UNITORGNAME);
        resultDTO.setData(item);
        return resultDTO;
    }
}
